import { SatConfigProvider, Table as SatTable, TimeShow } from '@tuya-sat/components';
import { Button, message, Space } from 'antd';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import api from '../../api';
import { microProps } from '../../index';
import styled from './index.module.less';

const TableList = function () {
  const [datas, setDatas] = useState([]);
  const { hasPermission } = microProps;

  const { t } = useTranslation();

  const columns = [
    {
      title: t('table.name'),
      dataIndex: 'user_nick_name',
      key: 'user_nick_name',
    },
    {
      title: t('table.username'),
      dataIndex: 'user_name',
      key: 'user_name',
    },
    {
      title: t('table.rolename'),
      dataIndex: 'role_name',
      key: 'role_name',
      render: (text, record) => {
        let name;
        if (record?.roles?.length) {
          name = record.roles[0].role_name;
        }
        return name;
      },
    },
    {
      title: t('table.create'),
      dataIndex: 'create_time',
      render: text => {
        return <TimeShow value={Number(text)} />;
      },
    },
    {
      title: t('table.action'),
      dataIndex: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Button
            type="link"
            disabled={!hasPermission('EDIT')}
            onClick={() => editUsers(record.user_id)}
          >
            {t('table.edit')}
          </Button>
          <Button
            type="link"
            disabled={!hasPermission('DELETE')}
            onClick={() => deleteUsers(record.user_id)}
          >
            {t('table.delete')}
          </Button>
        </Space>
      ),
    },
  ];

  function editUsers(userid) {
    api
      .put('/open-api/v1.0/users', {
        user_ids: userid,
      })
      .then(() => {
        const editPermission = hasPermission('EDIT');
        if (editPermission === false) {
          message.error(t('permission.title'));
        } else {
          message.success(t('permission.success'));
        }
      });
  }
  function deleteUsers() {
    const deletePermission = hasPermission('DELETE');
    if (deletePermission === false) {
      message.error(t('permission.title'));
    } else {
      message.success(t('permission.success'));
    }
  }

  function getList() {
    api
      .get('/open-api/v1.0/users')
      .then(res => {
        const registerPermission = hasPermission('REGISTER');
        if (!registerPermission) return setDatas('');
        setDatas(res.result.data);
      })
      .catch(e => console.log(e));
  }
  useEffect(() => {
    getList();
  }, []);

  return (
    <div className={styled['table']}>
      <SatConfigProvider
        antdConfigProvider={{
          renderEmpty: () => t('permission.title'),
        }}
      >
        <SatTable rowKey="user_id" columns={columns} dataSource={datas} />
      </SatConfigProvider>
    </div>
  );
};

export default TableList;
